package com.example.jd.finance.job;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.jd.common.enums.NumberEnum;
import com.example.jd.finance.entity.MsCustomerRecords;
import com.example.jd.finance.entity.MsCustomerRecordsPush;
import com.example.jd.finance.entity.MsWechatIncreaseFriends;
import com.example.jd.finance.entity.vo.FriendsResultVo;
import com.example.jd.finance.entity.vo.PushAppVo;
import com.example.jd.finance.jpush.PushClient;
import com.example.jd.finance.sever.MsCustomerRecordsService;
import com.example.jd.finance.sever.MsWechatIncreaseFriendsService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 右边为什么有黄线？
 * @author daolai.fu
 * @description 服务端下发任务到app端
 * @date 2021/11/8 13:13
 */

@RestController
@Slf4j
public class ServerIssueToAppJob {

    @Autowired
    private MsCustomerRecordsService msCustomerRecordsService;
    @Autowired
    private MsWechatIncreaseFriendsService msWechatIncreaseFriendsService;

    private static final int THIRTY = 30;
    private static final int TWENTY_THOUSAND = 20000;
    private static final int SUCCESS_CODE = 200;


    @Scheduled(cron = "0 */3 * * * ?")
    public void serverIssueToApp() {
        log.info("=====》定时任务查询得助客户数据开始===》");
        List<MsCustomerRecords> rl = msCustomerRecordsService.list(Wrappers.<MsCustomerRecords>lambdaQuery()
                .eq(MsCustomerRecords::getIssueState, NumberEnum.ONE.getCode()));
        log.info("===定时查询得助数据结果：{}", rl);
        if (CollectionUtils.isEmpty(rl)) {
            log.info("查询数据结果为空");
            return;
        }
        List<FriendsResultVo> dl = msWechatIncreaseFriendsService.queryListByCanDo();
        if (CollectionUtils.isEmpty(dl)) {
            log.info("====未查询到空闲设备====");
            return;
        }

        Gson gson = new Gson();
        List<PushAppVo> result = new ArrayList<>();
        if (rl.size() <= dl.size()) {
            this.forListGetResult(dl, rl, result);
        } else {
            whileAllList(dl, rl);
            addListForResultByFriend(dl, result);
        }

        log.info("定时任务封装参数为：{}", gson.toJson(result));
        this.pushResult(result);
    }


    private void whileAllList(List<FriendsResultVo> dl, List<MsCustomerRecords> rl) {
        while (rl.size() > NumberEnum.ZERO.getCode() && judgeBoolean(dl)) {
            for (FriendsResultVo f : dl) {
                int cy = TWENTY_THOUSAND - (f.getCumulativeIncreaseFriends() + f.getList().size());
                int ty = THIRTY - (f.getIncreaseFriendsTotalDay() + f.getList().size());
                if (!f.getFlag()) {
                    continue;
                }
                if (ty <= NumberEnum.ZERO.getCode() || cy <= NumberEnum.ZERO.getCode()) {
                    f.setFlag(false);
                    continue;
                }
                MsCustomerRecords r = rl.get(0);
                f.getList().add(MsCustomerRecordsPush.generateMsCustomerRecordsPush(r.getBid(), r.getCustomerEncryptWechatCode()));
                rl = rl.subList(1, rl.size());
                if (CollectionUtils.isEmpty(rl)) {
                    break;
                }
            }
        }
    }

    private void forListGetResult(List<FriendsResultVo> dl, List<MsCustomerRecords> rl, List<PushAppVo> result) {
        for (FriendsResultVo f : dl) {
            List<MsCustomerRecordsPush> list = new ArrayList<>();
            this.addListRecords(rl.subList(NumberEnum.ZERO.getCode(), NumberEnum.ONE.getCode()), list);

            result.add(PushAppVo.generatePushAppVo(f.getEnterpriseWechatCode(), f.getCurrentDevice(), list));
            rl = rl.subList(NumberEnum.ONE.getCode(), rl.size());
            if (CollectionUtils.isEmpty(rl)) {
                break;
            }
        }
    }

    private void addListForResultByFriend(List<FriendsResultVo> dl, List<PushAppVo> result) {
        for (FriendsResultVo f : dl) {
            result.add(PushAppVo.generatePushAppVo(f.getEnterpriseWechatCode(), f.getCurrentDevice(), f.getList()));
        }
    }

    private void pushResult(List<PushAppVo> result) {
        Gson gson = new Gson();
        if (!CollectionUtils.isEmpty(result)) {
            for (PushAppVo v : result) {
                if (SUCCESS_CODE == PushClient.AppSendPush(v.getCurrentDevice(), gson.toJson(v))) {
                    log.info("定时任务循环推送的任务为：{}", gson.toJson(v));
                    updateRecordsByBid(v.getList());
                }
            }
        }
    }

    private boolean judgeBoolean(List<FriendsResultVo> dl) {
        boolean flag = false;
        for (FriendsResultVo f : dl) {
            if (f.getFlag()) {
                flag = true;
                break;
            }
        }
        return flag;

    }

    @Scheduled(cron = "01 0 0 * * ?")
    public void updateCurrentDayFriendTotalEveryDay() {
        log.info("=====》定时任务更新好友当时增加数量开始start===》");
        MsWechatIncreaseFriends f = new MsWechatIncreaseFriends();
        f.setIncreaseFriendsTotalDay(NumberEnum.ZERO.getCode());
        f.setUpdateTime(LocalDateTime.now());
        msWechatIncreaseFriendsService.update(f, Wrappers.lambdaQuery());
        log.info("=====》定时任务更新好友当时增加数量结束end===》");
    }

    private void addListRecords(List<MsCustomerRecords> rl, List<MsCustomerRecordsPush> list) {
        for (MsCustomerRecords rd : rl) {
            list.add(MsCustomerRecordsPush.generateMsCustomerRecordsPush(rd.getBid(), rd.getCustomerEncryptWechatCode()));
        }

    }

    private void updateRecordsByBid(List<MsCustomerRecordsPush> list) {
        for (MsCustomerRecordsPush e : list) {
            MsCustomerRecords m = new MsCustomerRecords();
            m.setIssueState(NumberEnum.TWO.getCode());
            msCustomerRecordsService.update(m, Wrappers.<MsCustomerRecords>lambdaQuery()
                    .select()
                    .eq(MsCustomerRecords::getBid, e.getBid()));
        }

    }

}
